<template>
    <div class="container">
        <header>
            <h1>文件加解密工具</h1>
            <p class="subtitle">拖放文件到下方区域，选择操作后开始处理</p>
        </header>
        <!-- 密码输入区域 -->
        <div class="password-container" id="password-container">
            <div class="password-wrapper">
                <input :type="showPass ? 'text' : 'password'" autocomplete="new-password" id="password-input"
                    v-model="password" class="password-input" placeholder="请输入加密/解密密码">
                <i-material-symbols-visibility-outline-rounded class="fa toggle-password" @click="showPass = !showPass"
                    v-if="!showPass" />
                <i-material-symbols-visibility-off-outline class="fa toggle-password" @click="showPass = !showPass"
                    v-else />
            </div>
            <p class="password-hint">密码用于加密保护您的文件，请牢记密码</p>
        </div>
        <!-- 文件拖放区域（包含方块文件列表） -->
        <div class="drop-area" id="drop-area" @dragleave.prevent.stop="unheighlight"
            @drop.prevent.stop="unheighlight($event); handleDrap($event)" @dragenter.prevent.stop="heighlignt"
            @dragover.prevent.stop="heighlignt" @click="fileInput?.click()">
            <!-- 拖放提示（无文件时显示） -->
            <div class="drop-prompt" id="drop-prompt" v-show="!saveFiles.length">
                <div class="drop-icon">
                    <i-uiw-cloud-upload class="fa" />
                </div>
                <p class="drop-text">拖放文件到这里，或 <span class="browse-btn">浏览文件</span></p>
                <p class="drop-subtext">支持常见文件格式，大小不超过100MB</p>
            </div>

            <!-- 文件列表（方块网格布局） -->
            <div class="file-list" id="file-list" v-show="saveFiles" @click.stop="fileInput?.click()">
                <!-- 文件项将通过JS动态添加 -->
                <div class="file-item" v-for="file in saveFiles" @click.stop>
                    <div class="file-icon">
                        <component :is="getIcon(file.name)"></component>
                    </div>
                    <div class="file-info">
                        <div class="file-name">{{ file.name }}</div>
                        <div class="file-size">{{ formatFileSize(file.size) }}</div>
                    </div>
                    <div class="file-status">
                        <component class="fa fa-spin" :is="statusMap(processed.get(`${file.name}-${file.size}`)!)">
                        </component>
                    </div>
                    <div class="remove-file" @click="remove(`${file.name}-${file.size}`)">
                        <i-jam-close class="fa" />
                    </div>
                </div>
            </div>

            <input type="file" ref="fileInput" id="file-input" multiple @change="fileChange">
        </div>

        <!-- 进度条 -->
        <div class="progress-container" id="progress-container" v-show="processing">
            <div class="progress-info">
                <span class="progress-label" id="progress-label">处理中...</span>
                <span class="progress-percentage" id="progress-percentage">{{ progress }}%</span>
            </div>
            <div class="progress-bar">
                <div class="progress-fill" id="progress-fill" :style="{ width: progress + '%' }"></div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <button class="btn btn-primary" id="encrypt-btn" :disabled="!saveFiles.length || processing"
                @click="process" v-if="mode == 'encryption'">
                <i-bx-bxs-lock-alt class="fa fa-lock card-icon" /> 加密
            </button>
            <button class="btn btn-secondary" id="decrypt-btn" :disabled="!saveFiles.length || processing"
                @click="process" v-else>
                <i-si-unlock-muted-fill class="fa fa-unlock card-icon" /> 解密
            </button>
        </div>
    </div>
    <div class="footer">
        <p>© 2025 文件加解密工具</p>
    </div>
</template>
<script setup lang="ts">
import Loading from '~icons/eos-icons/bubble-loading'
import Android from '~icons/material-symbols/apk-document-outline'
import TxT from '~icons/line-md/text-box-multiple-to-text-box-transition'
import Doc from '~icons/icon-park-outline/file-doc'
import Pdf from '~icons/icon-park-outline/file-pdf-one'
import Img from '~icons/lets-icons/img-box-fill'
import Sound from '~icons/material-symbols/audio-file-outline'
import Video from '~icons/material-symbols/video-file-outline'
import Zip from '~icons/tdesign/file-zip'
import Exe from '~icons/qlementine-icons/executable-16'
import Code from '~icons/tabler/terminal-2'
import Excel from '~icons/ri/file-excel-2-line'
import Ppt from '~icons/ri/file-ppt-2-line'
import Db from '~icons/material-symbols/database'
import Html from '~icons/lineicons/html5'
import Css from '~icons/fluent/document-css-24-regular'
import Js from '~icons/fluent/document-javascript-24-regular'
import Vue from '~icons/vscode-icons/file-type-vue'
import Jsx from '~icons/file-icons/jsx-atom'
import C from '~icons/mdi/language-c'
import Cpp from '~icons/mdi/language-cpp'
import Java from '~icons/fluent/document-java-16-regular'
import Py from '~icons/mdi/language-python'
import Php from '~icons/simple-icons/php'
import Config from '~icons/eos-icons/configuration-file-outlined'
import Json from '~icons/lucide/file-json'
import Box from '~icons/carbon/3d-mpr-toggle'
import Default from '~icons/ic/baseline-insert-drive-file'
import Success from '~icons/ep/success-filled'
import Filled from '~icons/ix/namur-failure-filled'
import Clock from '~icons/material-symbols/nest-clock-farsight-analog-outline-rounded'
import { computed, defineComponent, h, reactive, ref, type FunctionalComponent } from 'vue'
interface EncryptionResult {
    id: string,
    arrayBuffer: ArrayBuffer,
    filename: string,
    ext: string,
    status: 'finish' | 'fail'
}
const props = defineProps<{
    mode: 'encryption' | "decrytion"
}>()
const password = ref('')
const showPass = ref(false)
let worker: Worker
if (props.mode == 'encryption') {
    worker = new Worker(new URL('../worker/Encryption.ts', import.meta.url), { type: 'module' })
} else {
    worker = new Worker(new URL('../worker/Decryption.ts', import.meta.url), { type: 'module' })
}
worker.addEventListener('message', (e: MessageEvent<EncryptionResult>) => {
    const { id, arrayBuffer, filename, ext, status } = e.data
    if (status == 'fail') {
        processed.set(id, 'fail')
        return
    }
    const blob = new Blob([arrayBuffer], { type: 'application/octet-stream' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    if (props.mode === 'decrytion') {
        a.download = `${filename}.${ext}`
    } else {
        a.download = `${filename}.bin`
    }
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    processed.set(id, 'finish')
})
const fileInput = ref<HTMLInputElement>()
const saveFiles = ref<File[]>([])
const processing = ref(false)
function createIcon(com: FunctionalComponent, color: string) {
    return defineComponent({
        render: () => h(com, { style: { color } })
    })
}
function statusMap(status: 'pending' | "finish" | 'fail' | 'unprocessed') {
    switch (status) {
        case 'pending':
            return createIcon(Loading, '#165DFF')
        case 'finish':
            return createIcon(Success, '#36D399')
        case "unprocessed":
            return createIcon(Clock, '#FBBD23')
        default:
            return createIcon(Filled, '#F87272')
    }
}
const processed = reactive(new Map<string, 'pending' | "finish" | 'fail' | 'unprocessed'>())
const progress = computed(() => {
    const total = processed.size
    const pendingCount = [...processed.values()].filter(v => v === 'pending').length

    const percent = total === 0 ? 0 : Math.floor((pendingCount / total) * 100)
    if(percent ==0){
        processing.value = false
    }
    return 100 - percent
})

function getIcon(filename: string) {
    const ext = filename.split('.').pop()?.toLowerCase()
    switch (ext) {
        case 'gltf':
        case 'glb':
            return Box;
        case "yaml":
        case 'xml':
        case 'json':
            return Json;
        case 'ini':
            return Config;
        case 'php':
            return Php;
        case 'py':
            return Py;
        case "java":
            return Java;
        case 'cpp':
            return Cpp;
        case 'c':
            return C;
        case 'jsx':
            return Jsx;
        case 'vue':
            return Vue;
        case 'apk':
            return Android;
        case "txt":
            return TxT;
        case "doc":
        case "docx":
            return Doc;
        case "pdf":
            return Pdf;
        case "jpg":
        case "jpeg":
        case "png":
        case "gif":
        case "bmp":
        case "svg":
        case "tiff":
            return Img;
        case "mp3":
        case 'wav':
        case 'aac':
        case 'flac':
        case 'ogg':
            return Sound;
        case 'mp4':
        case 'avi':
        case 'mkv':
        case "mov":
        case 'wmv':
            return Video;
        case 'zip':
        case 'rar':
        case '7z':
        case 'tar':
        case 'gz':
            return Zip;
        case 'exe':
        case "msi":
            return Exe;
        case "bat":
        case "sh":
            return Code;
        case "xls":
        case 'xlsx':
        case 'ods':
        case 'cvs':
            return Excel;
        case 'ppt':
        case 'odb':
            return Ppt;
        case 'sql':
        case 'mdb':
        case 'db':
            return Db;
        case 'html':
            return Html;
        case 'css':
            return Css;
        case 'js':
            return Js;
        default:
            return Default;
    }
}
// 格式化文件大小
function formatFileSize(bytes: number) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
function fileChange(e: Event) {
    const files = fileInput.value?.files
    if (files?.length) {
        handleFiles(files)
        if (e.target instanceof HTMLInputElement) {
            e.target.value = ''
        }
    }
}
function heighlignt(event: MouseEvent) {
    if (event.target instanceof HTMLDivElement) {
        event.target.classList.add('active')
    }
}
function unheighlight(event: MouseEvent) {
    if (event.target instanceof HTMLDivElement) {
        event.target.classList.remove('active')
    }
}
function readDirectory(
    entry: FileSystemDirectoryEntry,
    callback: (file: File) => void
) {
    const reader = entry.createReader();

    // WebKit 限制，需要多次 readEntries 才能读完
    const read = () => {
        reader.readEntries((entries) => {
            if (entries.length === 0) return;

            for (const e of entries) {
                if (e.isDirectory) {
                    readDirectory(e as FileSystemDirectoryEntry, callback);
                } else if (e.isFile) {
                    (e as FileSystemFileEntry).file(callback);
                }
            }

            // 继续读取剩余的
            read();
        });
    };

    read();
}
function handleDrap(e: DragEvent) {
    const dt = e.dataTransfer
    const files = dt?.files
    const items = Array.from(e.dataTransfer!.items);
    for (const item of items) {
        const entry = item.webkitGetAsEntry?.();
        if (!entry) continue;

        if (entry.isDirectory) {
            const isContenue = confirm('拖入的是一个文件夹，当前暂未支持导出文件夹，只能以扁平的零散文件导出，是否继续?')
            if (isContenue) {

                readDirectory(entry as FileSystemDirectoryEntry, (file) => {
                    handleFiles(file)

                });
            }
        } else if (entry.isFile) {
            if (files?.length) {
                handleFiles(files)
            }
        }
    }

}
function handleFiles(files: FileList | File) {
    if (files instanceof FileList) {
        for (let i = 0; i < files.length; i++) {
            const file = files[i]
            if (!saveFiles.value.some(item => item.name === file?.name && item.size === file.size)) {
                saveFiles.value.push(file!)
                processed.set(`${file?.name}-${file?.size}`, 'unprocessed')
            }

        }
    } else {
        saveFiles.value.push(files!)
        processed.set(`${files?.name}-${files?.size}`, 'unprocessed')
    }

}
function remove(id: string) {
    saveFiles.value = saveFiles.value.filter(file => `${file.name}-${file.size}` !== id)
}
function process() {
    if (!password.value) {
        alert('请填写密码')
        return
    }
    processing.value = true
    processed.forEach((_item, key) => {
        processed.set(key, 'pending')
    })
    saveFiles.value.forEach(async item => {
        worker.postMessage({ arrayBuffer: await item.arrayBuffer(), password: password.value, id: `${item.name}-${item.size}` },)
    })
}
</script>
<style>
:root {
    --primary: #165DFF;
    --primary-light: #E8F3FF;
    --success: #36D399;
    --danger: #F87272;
    --warning: #FBBD23;
    --dark: #1E293B;
    --gray: #64748B;
    --light-gray: #F1F5F9;
    --white: #FFFFFF;
    --shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    --shadow-hover: 0 8px 30px rgba(0, 0, 0, 0.12);
    --transition: all 0.3s ease;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Inter', system-ui, -apple-system, sans-serif;
}

/* 密码输入区域 */
.password-container {
    margin-bottom: 2rem;
    /* 默认隐藏 */
}

.password-container.visible {
    display: block;
}

.password-wrapper {
    position: relative;
    max-width: 400px;
    margin: 0 auto;
}

.password-input {
    width: 100%;
    padding: 0.8rem 1rem 0.8rem 1rem;
    border-radius: 8px;
    border: 1px solid var(--gray);
    font-size: 1rem;
    transition: var(--transition);
    padding-right: 3rem;
    /* 预留图标空间 */
}

.password-input:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(22, 93, 255, 0.1);
}

.toggle-password {
    position: absolute;
    right: 0.8rem;
    top: 50%;
    transform: translateY(-50%);
    color: var(--gray);
    cursor: pointer;
    transition: var(--transition);
}

.toggle-password:hover {
    color: var(--primary);
}

.password-hint {
    margin-top: 0.5rem;
    font-size: 0.85rem;
    color: var(--gray);
    text-align: center;
}

html,
body {
    height: 100%;
}

body {
    background-color: #FAFAFA;
    color: var(--dark);
    line-height: 1.6;
    display: flex;
    flex-direction: column;
}
</style>
<style scoped>
.container {
    width: 100%;
    max-width: 900px;
    margin: 0 auto;
    padding: 2rem 1rem;
    flex-grow: 1;
    flex: 1;
    display: flex;
    flex-direction: column;
}

header {
    text-align: center;
    margin-bottom: 2.5rem;
}

h1 {
    font-size: 2rem;
    font-weight: 700;
    color: var(--dark);
    margin-bottom: 0.5rem;
}

.subtitle {
    color: var(--gray);
    font-size: 1rem;
}

/* 拖放区域样式 - 方块文件容器 */
.drop-area {
    border: 2px dashed var(--primary);
    border-radius: 12px;
    padding: 2rem;
    text-align: center;
    background-color: var(--primary-light);
    transition: var(--transition);
    cursor: pointer;
    margin-bottom: 2rem;
    min-height: 320px;
    display: flex;
    flex-direction: column;
}

.drop-area:hover {
    background-color: rgba(22, 93, 255, 0.15);
    transform: translateY(-2px);
}

.drop-area.active {
    border-style: solid;
    background-color: rgba(22, 93, 255, 0.2);
}

/* 拖放提示（无文件时显示） */
.drop-prompt {
    margin: auto;
    transition: var(--transition);
}

.drop-icon {
    font-size: 3rem;
    color: var(--primary);
    margin-bottom: 1rem;
    transition: var(--transition);
}

.drop-area:hover .drop-icon {
    transform: scale(1.05);
}

.drop-text {
    font-size: 1.1rem;
    font-weight: 500;
    color: var(--dark);
    margin-bottom: 0.5rem;
}

.drop-subtext {
    font-size: 0.9rem;
    color: var(--gray);
}

.browse-btn {
    color: var(--primary);
    font-weight: 600;
    cursor: pointer;
    text-decoration: underline;
}

/* 文件列表样式 - 方块网格布局 */
.file-list {
    width: 100%;
    margin-top: 1rem;
    /* 默认隐藏 */
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    /* 自动填充方块 */
    gap: 1rem;
    overflow-y: auto;
    display: grid;
    max-height: 280px;
    padding: 0.5rem;
}

.file-list.has-files {
    display: grid;
    /* 有文件时显示网格 */
}

/* 方块文件项样式 */
.file-item {
    background-color: var(--white);
    border-radius: 8px;
    padding: 1rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    position: relative;
    min-height: 140px;
    transition: var(--transition);
}

.file-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.file-icon {
    font-size: 2rem;
    color: var(--primary);
    margin-bottom: 0.8rem;
    flex-grow: 1;
    display: flex;
    align-items: center;
}

.file-info {
    width: 100%;
    margin-bottom: 0.5rem;
}

.file-name {
    font-weight: 500;
    font-size: 0.9rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 0.2rem;
}

.file-size {
    font-size: 0.75rem;
    color: var(--gray);
}

.file-status {
    position: absolute;
    bottom: 0.8rem;
    right: 0.8rem;
    font-size: 1rem;
}

.status-pending {
    color: var(--warning);
}

.status-processing {
    color: var(--primary);
}

.status-success {
    color: var(--success);
    animation: fadeIn 0.5s ease;
}

.status-error {
    color: var(--danger);
}

.remove-file {
    position: absolute;
    top: 0.5rem;
    right: 0.5rem;
    color: var(--gray);
    cursor: pointer;
    opacity: 0.7;
    transition: var(--transition);
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.03);
}

.remove-file:hover {
    color: var(--danger);
    opacity: 1;
    background-color: rgba(0, 0, 0, 0.05);
}

/* 进度条样式 */
.progress-container {
    margin-bottom: 2rem;
}

.progress-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
    font-size: 0.9rem;
}

.progress-label {
    font-weight: 500;
}

.progress-percentage {
    color: var(--primary);
    font-weight: 600;
}

.progress-bar {
    height: 8px;
    background-color: var(--light-gray);
    border-radius: 4px;
    overflow: hidden;
}

.progress-fill {
    height: 100%;
    background-color: var(--primary);
    border-radius: 4px;
    width: 0%;
    transition: width 0.3s ease;
}

/* 按钮样式 */
.action-buttons {
    display: flex;
    gap: 1rem;
    justify-content: center;
}

.btn {
    padding: 0.8rem 2rem;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    transition: var(--transition);
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

.btn-primary {
    background-color: var(--primary);
    color: var(--white);
}

.btn-primary:hover {
    background-color: #0E4CD1;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(22, 93, 255, 0.3);
}

.btn-secondary {
    background-color: var(--white);
    color: var(--primary);
    border: 1px solid var(--primary);
}

.btn-secondary:hover {
    background-color: var(--primary-light);
    transform: translateY(-2px);
}

.btn:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

/* 底部版权信息 */
.footer {
    text-align: center;
    font-size: 0.85rem;
    color: var(--gray);
    padding: 1.5rem;
    border-top: 1px solid rgba(0, 0, 0, 0.05);
    margin-top: auto;
}

/* 动画效果 */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: scale(0.8);
    }

    to {
        opacity: 1;
        transform: scale(1);
    }
}

/* 响应式设计 */
@media (max-width: 600px) {
    h1 {
        font-size: 1.6rem;
    }

    .drop-area {
        padding: 1.5rem;
        min-height: 280px;
    }

    .drop-icon {
        font-size: 2.5rem;
    }

    .action-buttons {
        flex-direction: column;
    }

    .btn {
        width: 100%;
        padding: 0.7rem 1rem;
    }

    .file-list {
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    }
}

/* 隐藏实际文件输入 */
#file-input {
    display: none;
}
</style>